//
//  XFXViewAndVoiceViewController.m
//  
//
//  Created by dllo on 16/1/26.
//  Copyright © 2016年 lanou. All rights reserved.
//

#import "XFXViewAndVoiceViewController.h"

#import "XFXViewTableViewCell.h"
#import "XFXAppTools.h"

#import "XFXtittleView.h"
#import "XFXDetailPageVoiceViewController.h"
#import "XFXDidVoiceViewController.h"

#import "XFXtittleModel.h"
#import "XFXVoiceModel.h"
#import <AVFoundation/AVFoundation.h>



@interface XFXViewAndVoiceViewController ()
<
    XFXtittleViewDelegate,
    XFXViewTableViewCellDelegate,
    UITableViewDelegate,
    UITableViewDataSource

>

@property (nonatomic, strong) UITableView *myTableView;
@property (nonatomic, strong) XFXtittleView *myView;
@property (nonatomic, strong) NSMutableArray *allArray;
@property (nonatomic, strong) NSMutableArray *videoArray;

@property (nonatomic,retain)AVPlayerItem *playerItem;// 设置播放器播放项目的类,设置播放视频资源
@property (nonatomic,retain)AVPlayer *player;// 视频播放器对象
@property (nonatomic,retain)AVPlayerLayer *playerLayer;// 设置承载显示视频播放器的类
@property (nonatomic,assign)CGFloat totalDuration; // 记录总时长
@property (nonatomic,assign)BOOL isPlaying;   // 记录播放状态

@property (nonatomic,retain)UIView *bottomView;
@property (nonatomic,retain)UISlider *progressSlider;
@property (nonatomic,retain)UIButton *button;
@property (nonatomic,retain)UILabel *currentTime;
@property (nonatomic,retain)UILabel *currenTime;
@property (nonatomic, copy)NSString *currentUrlString;
@property (nonatomic,retain)UIView *viedoView;
@property (nonatomic,retain)AVPlayerLayer *layerAV;

@property (nonatomic,retain) UIView *playerView;


@end

@implementation XFXViewAndVoiceViewController


- (void)viewDidLoad {
    [super viewDidLoad];

    self.navigationController.navigationBar.barTintColor = [UIColor redColor];
    self.navigationItem.title = @"视频";
    
    self.allArray = [NSMutableArray array];
    self.videoArray = [NSMutableArray array];
    
    
    self.myTableView = [[UITableView alloc] initWithFrame:[[UIScreen mainScreen]bounds] style:UITableViewStylePlain];
    self.myTableView.delegate =self;
    self.myTableView.dataSource =self;
    
    UINib *nib = [UINib nibWithNibName:@"XFXViewTableViewCell" bundle:[NSBundle mainBundle]];
    [self.myTableView registerNib:nib forCellReuseIdentifier:@"cell"];
    
    self.isUpLoading = NO;
    
    [self addheader];
    [self addfooter];
    self.myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [self.view addSubview:self.myTableView];
    
    
    self.myView = [[XFXtittleView alloc]initWithFrame:CGRectMake(0, 0, XFXWIDTH, 150*XFXHEIGHT/736)];
    self.myView.delegate = self;
    self.myTableView.tableHeaderView = self.myView;
   
}

- (void)getValue:(NSInteger )page{
    
    NSString *url = [NSString stringWithFormat:@"http://c.3g.163.com/nc/video/home/%ld-10.html",(long)page*10];

    [XFXAppTools getNewsWithHeadline:url block:^(id reulst) {
        if (self.isUpLoading==NO) {
            [self.videoArray removeAllObjects];
        }
        NSMutableArray *videoSidList = [reulst objectForKey:@"videoSidList"];
        for (NSDictionary *dic in videoSidList) {
            XFXtittleModel *model = [[XFXtittleModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.allArray addObject:model];
        }
         self.myView.array = self.allArray;
        NSMutableArray *videoList = [reulst objectForKey:@"videoList"];
        for (NSDictionary *dic in videoList) {
            XFXVoiceModel *model = [[XFXVoiceModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.videoArray addObject:model];

        }
        [_myTableView headerEndRefreshing];
        [_myTableView footerEndRefreshing];
        [_myTableView reloadData];
    } error:^(NSError *error) {
        
    }];
   
}

-(void)addheader{

    __block XFXViewAndVoiceViewController *vc = self;
    [_myTableView addHeaderWithCallback:^{
        vc.page = 0;
        vc.isUpLoading = NO;
        [vc getValue:vc.page];
    }];
    
    [_myTableView headerBeginRefreshing];
}

- (void)addfooter{
    
    __block XFXViewAndVoiceViewController *vc = self;
    [_myTableView addFooterWithCallback:^{
        
        vc.page ++;
        vc.isUpLoading = YES;
        [vc getValue:vc.page];
    }];
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 300*XFXHEIGHT/736;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.videoArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    XFXViewTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];

    self.myImage = cell.playerImage;

    cell.delegate = self;
    cell.indexPath = indexPath;
    cell.model = self.videoArray[indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [self.player pause];
    
    XFXVoiceModel *model= [self.videoArray objectAtIndex:indexPath.row];
    XFXDidVoiceViewController *mediaDetail = [[XFXDidVoiceViewController alloc] init];
    mediaDetail.model = model;
 
    self.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:mediaDetail animated:YES];
    self.hidesBottomBarWhenPushed = NO;
   
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    

}


#pragma 4个图片协议点击
- (void)send:(XFXtittleModel *)value{
    
    [self.player pause];
    XFXDetailPageVoiceViewController *deta = [[XFXDetailPageVoiceViewController alloc]init];
    deta.model = value;
    self.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:deta animated:YES];
    self.hidesBottomBarWhenPushed = NO;
}



#pragma mark -- 懒加载创建视频视图对象
-(UIView *)playerView {
    
    if (nil == _playerView) {
        _playerView = [[UIView alloc] init];
    }
    return _playerView;
}

#pragma mark-- 自定义创建视频播放器传入url
-(void)show:(NSIndexPath *)indexPath{

    
    
    
    self.indexPath = indexPath.row;
    XFXVoiceModel *model= [self.videoArray objectAtIndex:indexPath.row];
    self.playerView.frame = CGRectMake(5, 195*XFXHEIGHT/736 + 300*XFXHEIGHT/736 * indexPath.row, XFXWIDTH-10, self.myImage.frame.size.height);


    [self.myTableView addSubview:self.playerView];
    self.bottomView.frame = CGRectMake(0, self.playerLayer.frame.size.height-30, self.playerView.frame.size.width, 30);
    // 判断播放URL传入url是否相等
    if (![model.mp4_url isEqualToString:self.currentUrlString]) {
        self.currentUrlString = model.mp4_url;
        NSURL *url = [NSURL URLWithString:model.mp4_url];
        self.playerItem = [AVPlayerItem playerItemWithURL:url];
        
        if (_player == nil) {
            
            self.player = [AVPlayer playerWithPlayerItem:self.playerItem];
            self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
            self.playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
            self.playerLayer.frame = self.playerView.bounds;
            [self.playerView.layer addSublayer:self.playerLayer];
            self.bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, self.playerLayer.frame.size.height-30, self.playerView.frame.size.width, 30)];
            self.bottomView.backgroundColor = [UIColor grayColor];
            
            [self.playerView addSubview:self.bottomView];
            self.progressSlider = [[UISlider alloc] initWithFrame:CGRectMake(30,0, XFXWIDTH-60, 30)];
            [self.progressSlider setThumbImage:[UIImage imageNamed:@"iconfont-yuandian.png"] forState:UIControlStateNormal];
            self.progressSlider.backgroundColor = [UIColor clearColor];
            self.progressSlider.alpha = 0.5;
            self.progressSlider.value = 0;
            [self.bottomView addSubview:self.progressSlider];
            self.progressSlider.maximumValue = 1;
            self.progressSlider.minimumValue = 0;
            [self.progressSlider addTarget:self action:@selector(progressAction:) forControlEvents:UIControlEventValueChanged];
            [self showPlayerProgress];
            
            self.button = [UIButton buttonWithType:UIButtonTypeCustom];
            self.button.frame = CGRectMake(0, 0, 30, self.bottomView.frame.size.height);

            [self.button setImage:[UIImage imageNamed:@"iconfont-zanting.png"] forState:UIControlStateNormal];
            [self.bottomView addSubview:self.button];
            [self.button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
            
            
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
            [self.playerView addGestureRecognizer:tap];
            
        } else {
            // 播放视频源数据
            [self.player replaceCurrentItemWithPlayerItem:self.playerItem];
            
            
        }
        
    }
    [self.player play];
    self.isPlaying = NO;
    

}


#pragma  mark -- 轻拍手势
- (void)tapAction:(UITapGestureRecognizer *)tap{
    
    if (self.bottomView.alpha==0) {
        
        [UIView animateWithDuration:1 animations:^{
            
            self.bottomView.alpha = 1;
        }];
    }else{
        
        [UIView animateWithDuration:1 animations:^{
            
            self.bottomView.alpha = 0;
        }];
    }
    
    
}

#pragma  mark -- slider
- (void)progressAction:(UISlider *)slider{
    
    double currentnTime = slider.value * self.totalDuration;
    
    CMTime time = CMTimeMake(currentnTime, 1);
    
    [self.player seekToTime:time completionHandler:^(BOOL finished) {
        
        [self.player play];
    }];
}

- (void)showPlayerProgress{
    
    __block XFXViewAndVoiceViewController *vc = self;
    CMTime time = CMTimeMake(1, 1);
    [self.player addPeriodicTimeObserverForInterval:time queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        
        CMTime currenTime = vc.playerItem.currentTime;
        
        CMTime totalTime = vc.playerItem.duration;
        
        double currentT = CMTimeGetSeconds(currenTime);
        double totalT = CMTimeGetSeconds(totalTime);
        
        vc.progressSlider.value = currentT/totalT;
        
        vc.totalDuration = totalT;
    }];
    
}

- (void)buttonAction:(UIButton *)bnt{
    
    if (self.isPlaying == NO) {
        
        [self.player play];
        
        [self.button setImage:[UIImage imageNamed:@"iconfont-zanting.png"] forState:UIControlStateNormal];
    }else{
        
        [self.player pause];
        
        [self.button setImage:[UIImage imageNamed:@"iconfont-bofangqibofang.png"] forState:UIControlStateNormal];
    }
    
    self.isPlaying = !self.isPlaying;
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [UIView animateWithDuration:1 animations:^{
            
            self.bottomView.alpha = 0;
        }];
        
    });
    
    
}





#pragma mark -- 滚动时创建小视频

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{

    if (self.playerView.frame.size.height != 0) {


        if (scrollView.contentOffset.y > XFXHEIGHT*0.15 + XFXHEIGHT*0.45*self.indexPath+self.playerView.frame.size.height-64) {


            XFXVoiceModel *model = [self.videoArray objectAtIndex:self.indexPath];

            [self withWithUrl:model.mp4_url];

        }else{
       
            [self.viedoView removeFromSuperview];
        }

    }

}
#pragma 创建小视频
- (void)withWithUrl:(NSString *)str{
    
    if (!self.viedoView) {
        
//        self.viedoView = [[UIView alloc]init];
        self.viedoView = [[UIView alloc] initWithFrame:CGRectMake(XFXWIDTH-130*XFXWIDTH/414, XFXHEIGHT-120*XFXHEIGHT/736, 100*XFXWIDTH/414, 50*XFXHEIGHT/736)];
        
//        [self.viedoView mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.right.equalTo(self.view.right).offset(-30);
//            make.bottom.equalTo(self.view.bottom).offset(-100);
//            make.width.equalTo(@100);
//            make.height.equalTo(@50);
//            
//        }];
        
        self.layerAV = [AVPlayerLayer playerLayerWithPlayer:self.player];
        self.layerAV.frame = self.viedoView.bounds;
        self.layerAV.videoGravity = AVLayerVideoGravityResizeAspectFill;
        [self.viedoView.layer addSublayer:self.layerAV];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapleftAction:)];
        [self.viedoView addGestureRecognizer:tap];
    }
    [self.view addSubview:self.viedoView];
    
}

#pragma 小视频轻拍
- (void)tapleftAction:(UITapGestureRecognizer *)tap{
    
    [self.player pause];
    
    XFXVoiceModel *model= [self.videoArray objectAtIndex:self.indexPath];
    XFXDidVoiceViewController *mediaDetail = [[XFXDidVoiceViewController alloc] init];
    mediaDetail.model = model;
    
    self.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:mediaDetail animated:YES];
    self.hidesBottomBarWhenPushed = NO;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
